package com.mezz.bones.im.gateway.action.impl;


import com.mezz.bones.im.common.enums.ActionCodeEnum;
import com.mezz.bones.im.common.message.base.MessageHeader;
import com.mezz.bones.im.common.message.body.in.PingReq;
import com.mezz.bones.im.common.domain.user.ImUserConnectInfo;
import com.mezz.bones.im.common.result.ImResult;
import com.mezz.bones.im.gateway.service.IUserStatusService;
import com.mezz.bones.im.gateway.action.interfaces.AbstractSysMessageAction;
import com.mezz.bones.im.gateway.manager.UserConnectInfoManager;
import com.mezz.bones.im.gateway.manager.UserIpManager;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: zhuang
 * @Date: 2024/11/29 18:39
 * @Description: TODO
 * @Version: 1.0
 **/

@Service
public class PingSysAction extends AbstractSysMessageAction<PingReq> {
    @Resource
    private UserConnectInfoManager userConnectInfoManager;

    @Resource
    private IUserStatusService userStatusService;

    @Resource
    private UserIpManager userIpManager;

    @Override
    public String tag() {
        return ActionCodeEnum.CLIENT_PING_PONG.getCode();
    }

    @Override
    public void process(MessageHeader header, PingReq req, ChannelHandlerContext ctx) {

        ImUserConnectInfo userConnectInfo = userConnectInfoManager.getUserConnectInfo(ctx);
        if(userConnectInfo != null){
            //可能用户还未认证
            String ip = userIpManager.getIp(ctx);
            //更新在线状态
            userStatusService.online(userConnectInfo,ctx,ip);
        }
        //发送pong事件到客户端
        ctx.channel().writeAndFlush(ImResult.ok(header.getTraceId(),ActionCodeEnum.CLIENT_PING_PONG.getCode(),null));
    }
}
